package cn.edu.tju.elm.service.Impl;

import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.model.BusinessApplication;
import cn.edu.tju.elm.repository.BusinessApplicationRepository;
import cn.edu.tju.elm.service.BusinessApplicationService;
import cn.edu.tju.core.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

import cn.edu.tju.core.model.User;
import cn.edu.tju.core.model.Authority;
import cn.edu.tju.elm.model.BusinessApplication;
import cn.edu.tju.elm.repository.BusinessApplicationRepository;
import cn.edu.tju.elm.service.BusinessApplicationService;
import cn.edu.tju.core.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class BusinessApplicationServiceImpl implements BusinessApplicationService {

    private final BusinessApplicationRepository businessApplicationRepository;

    @Autowired
    private UserService userService;

    @Autowired
    public BusinessApplicationServiceImpl(BusinessApplicationRepository businessApplicationRepository) {
        this.businessApplicationRepository = businessApplicationRepository;
    }

    @Override
    public BusinessApplication save(BusinessApplication application) {
        return businessApplicationRepository.save(application);
    }

    @Override
    public Optional<BusinessApplication> findById(Long id) {
        return businessApplicationRepository.findById(id);
    }

    @Override
    public List<BusinessApplication> findByApplicantId(Long applicantId) {
        return businessApplicationRepository.findByApplicantIdOrderByCreateTimeDesc(applicantId);
    }

    @Override
    public List<BusinessApplication> findByStatus(Integer status) {
        return businessApplicationRepository.findByStatusOrderByCreateTimeDesc(status);
    }

    @Override
    public List<BusinessApplication> findAll() {
        return businessApplicationRepository.findAll();
    }

    @Override
    @Transactional
    public BusinessApplication updateApplication(Long id, BusinessApplication application) {
        Optional<BusinessApplication> existingApplicationOpt = businessApplicationRepository.findById(id);
        if (!existingApplicationOpt.isPresent()) {
            throw new RuntimeException("开店申请不存在");
        }

        BusinessApplication existingApplication = existingApplicationOpt.get();

        // 获取当前用户
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null || !existingApplication.getApplicant().getId().equals(currentUser.getId())) {
            throw new RuntimeException("只能修改自己的开店申请");
        }

        // 只能修改待审核状态的申请
        if (existingApplication.getStatus() != 0) {
            throw new RuntimeException("只能修改待审核状态的申请");
        }

        // 更新字段
        if (application.getBusinessName() != null) {
            existingApplication.setBusinessName(application.getBusinessName());
        }
        if (application.getBusinessAddress() != null) {
            existingApplication.setBusinessAddress(application.getBusinessAddress());
        }
        if (application.getBusinessDescription() != null) {
            existingApplication.setBusinessDescription(application.getBusinessDescription());
        }
        if (application.getBusinessImage() != null) {
            existingApplication.setBusinessImage(application.getBusinessImage());
        }
        if (application.getOrderTypeId() != null) {
            existingApplication.setOrderTypeId(application.getOrderTypeId());
        }
        if (application.getStartPrice() != null) {
            existingApplication.setStartPrice(application.getStartPrice());
        }
        if (application.getDeliveryPrice() != null) {
            existingApplication.setDeliveryPrice(application.getDeliveryPrice());
        }
        if (application.getContactInfo() != null) {
            existingApplication.setContactInfo(application.getContactInfo());
        }
        if (application.getIdCardFront() != null) {
            existingApplication.setIdCardFront(application.getIdCardFront());
        }
        if (application.getIdCardBack() != null) {
            existingApplication.setIdCardBack(application.getIdCardBack());
        }
        if (application.getBusinessLicense() != null) {
            existingApplication.setBusinessLicense(application.getBusinessLicense());
        }

        existingApplication.setUpdateTime(LocalDateTime.now());
        existingApplication.setUpdater(currentUser.getId());

        return businessApplicationRepository.save(existingApplication);
    }

    @Override
    @Transactional
    public BusinessApplication submitApplication(BusinessApplication application) {
        User currentUser = userService.getUserWithAuthorities().orElse(null);
        if (currentUser == null) {
            throw new RuntimeException("用户未登录");
        }

        // 设置申请人
        application.setApplicant(currentUser);

        // 设置状态为待审核
        application.setStatus(0);

        // 设置审计字段
        LocalDateTime now = LocalDateTime.now();
        if (application.getId() == null) {
            application.setCreateTime(now);
            application.setCreator(currentUser.getId());
        }
        application.setUpdateTime(now);
        application.setUpdater(currentUser.getId());
        application.setDeleted(false);

        return businessApplicationRepository.save(application);
    }

    @Override
    @Transactional
    public BusinessApplication reviewApplication(Long id, Integer status, String reviewComment, Long reviewerId) {
        Optional<BusinessApplication> applicationOpt = businessApplicationRepository.findById(id);
        if (!applicationOpt.isPresent()) {
            throw new RuntimeException("开店申请不存在");
        }

        BusinessApplication application = applicationOpt.get();

        // 验证状态值
        if (status < 1 || status > 2) {
            throw new RuntimeException("无效的审核状态");
        }

        // 保存原始状态，用于判断是否需要更新权限
        Integer originalStatus = application.getStatus();

        application.setStatus(status);
        application.setReviewComment(reviewComment);
        application.setReviewerId(reviewerId);
        application.setUpdateTime(LocalDateTime.now());
        application.setUpdater(reviewerId);

        BusinessApplication savedApplication = businessApplicationRepository.save(application);

        // 如果审核通过（状态从非1变为1），为用户添加BUSINESS权限
        if (status == 1 && originalStatus != 1) {
            addBusinessAuthorityToUser(application.getApplicant());
        }

        return savedApplication;
    }

    /**
     * 为用户添加BUSINESS权限
     */
    private void addBusinessAuthorityToUser(User user) {
        try {
            // 检查用户是否已经有BUSINESS权限
            boolean hasBusinessAuthority = user.getAuthorities().stream()
                    .anyMatch(authority -> "BUSINESS".equals(authority.getName()));

            if (!hasBusinessAuthority) {
                // 为用户添加BUSINESS权限
                userService.addAuthorityToUser(user.getUsername(), "BUSINESS");
            }
        } catch (Exception e) {
            // 记录错误但不中断审核流程
            System.err.println("为用户添加BUSINESS权限失败: " + e.getMessage());
            e.printStackTrace();
        }
    }


    @Override
    public Optional<BusinessApplication> findByIdAndApplicantId(Long id, Long applicantId) {
        return businessApplicationRepository.findByIdAndApplicantId(id, applicantId);
    }
}